package kr.saeildamil.androidStudy_second.draw;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Canvas;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;

public class MyView extends View {
	ArrayList<Ball> arBall;
	final static int DELAY = 50;

	public MyView(Context context) {
		super(context);
		arBall = new ArrayList<Ball>();
		mHandler.sendEmptyMessageDelayed(0, DELAY);
	}

	public boolean onTouchEvent(android.view.MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			Ball newBall = new Ball((int) event.getX(), (int) event.getY());
			arBall.add(newBall);
			invalidate(); // onDraw()를 호출하여 추가된 볼을 그려주도록 하는 역할
			return true;
		}
		return false;

	};

	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		for (int i = 0; i < arBall.size(); i++) {
			arBall.get(i).Draw(canvas); // ArrayList의 갯수만큼 볼을 그려준다.
		}
	};

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Ball B;
			for (int i = 0; i < arBall.size(); i++) {
				B = arBall.get(i);
				B.Move(getWidth(), getHeight()); // 볼이 이동한다.ㅋㅋ
				if (B.count > 4) {
					arBall.remove(i);
					i--;
				}
			}
			invalidate();
			mHandler.sendEmptyMessageDelayed(0, DELAY);
		}

	};

}
